<template>
	<s-layout :bgStyle="{ color: '#fff' }" tabbar="/pages/index/lifecircle" title="商家联盟">
		<view class="s-category">
			<!-- 轮播图模块 -->
			<swiper class="swiper-wrap" autoplay circular indicator-dots>
				<swiper-item v-for="(item, index) in state.bannerList" :key="index">
					<image class="swiper-img" :src="item.picUrl" mode="aspectFill" />
				</swiper-item>
			</swiper>

			<!-- 分类导航模块 -->
			<!-- <view class="grid-wrap">
				<view class="grid-item" v-for="(item, index) in state.gridList" :key="index"
					@tap="filterByType(item.id)" :class="{ 'active-grid': state.activeType  === item.id  }">
					<view class="icon-wrapper">
						<image class="grid-icon" :src="item.picUrl" mode="aspectFit" />
					</view>
					<view class="text-wrapper">
						<text class="grid-text">{{ item.typeName  }}</text>
					</view>
				</view>
			</view> -->

			<view class="locate" @tap="getLocateMore()">
				<image class="locate-icon" src="/static/lifecircle/locate-icon.png" mode="widthFix" />
				<view class="locate-content">{{locateContent}}</view>
				<image class="locate-icon" src="/static/lifecircle/more.png" mode="widthFix" />
			</view>

			<view>
				<ScrollTop :tabs="state.gridList" @currentIndex="filterByType" />
			</view>

			<!-- 店铺列表模块 -->
			<view class="bottom-wrap">
				<view class="tab-bar">
					<view class="tab-item">
						<image class="title-icon" src="/static/images/lifecirclestore.png" mode="widthFix" />
						<text class="text-with-shadow">店铺列表</text>
					</view>

					<view class="search-box">
						<image class="search-icon" src="/static/images/search.png" mode="aspectFit" />
						<input class="search-input" placeholder="请输入店铺名称" placeholder-style="color:#999;font-size:28rpx"
							v-model="state.searchKeyword" @input="handleSearch" />
					</view>
				</view>

				<view class="shop-list">
					<view class="shop-card" v-for="shop in state.shopList" :key="shop.id"
						@tap="sheep.$router.go('/pages/index/life_store_detail',  { id: shop.id  })">
						<image class="shop-card__thumb" :src="shop.imageUrl" mode="aspectFill" lazy-load />

						<view class="shop-card__info">
							<view class="name-status-wrapper">
								<text class="shop-card__name line-clamp-1">{{ shop.name  }}</text>
								<view class="shop-card__status" :class="shop.status  === 0 ? 'active' : 'inactive'">
									{{ shop.status  === 0 ? '🟢 营业中' : '🔴 已打烊' }}
								</view>
							</view>

							<view class="star-rating">
								<image v-for="n in 5" :key="n" class="star-icon" src="/static/images/star.png"
									mode="widthFix" />
							</view>

							<view class="shop-card__meta">
								<view class="meta-left">
									<view class="address-container">
										<text class="shop-card__address line-clamp-1">{{ shop.address  }}</text>
										<view class="distance-info">
											<image class="location-icon" src="/static/images/pos_green.png"
												mode="widthFix" />
											<text class="distance-text">{{ shop.distance  }}</text>
										</view>
									</view>
									<view class="discount-tags" v-if="shop.discounts?.length  > 0">

										<text v-for="(points, idx) in shop.discounts" :key="idx" class="discount-tag">
											<text class="discount-tag-text">积</text>
											<text class="discount-tag-num">{{ points.pointsValue  }}%</text>

										</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</s-layout>
</template>

<script setup>
	import sheep from '@/sheep';
	import LifeCircleApi from '@/sheep/api/product/lifecircle';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import ScrollTop from './components/scroll-tabs';
	import amap from '@/libs/amap-uni.js';
	import {
		reactive,
		ref
	} from 'vue';

	const state = reactive({
		bannerList: [],
		gridList: [{
			id: 0,
			typeName: '全部',
			picUrl: '/static/images/search.png'
		}],
		shopList: [],
		originalShopList: [],
		activeType: null,
		searchKeyword: ''
	});

	const locateContent = ref()
	const myAmapFun = ref()
	const lngLat = ref([])

	const handleSearch = () => {
		state.shopList = state.originalShopList.filter(shop => {
			const matchType = !state.activeType || shop.typeId === state.activeType;
			const matchKeyword = shop.name.includes(state.searchKeyword);
			return matchType && matchKeyword;
		});
	};

	// 分类筛选功能 
	const filterByType = (typeId) => {
		state.activeType = typeId;
		state.shopList = typeId
		applyFilters(); // 改为调用统一过滤方法 
		// ? state.originalShopList.filter(shop  => shop.typeId  === typeId)
		// : [...state.originalShopList]; 
	};

	// 新增统一过滤方法 
	const applyFilters = () => {
		state.shopList = state.originalShopList.filter(shop => {
			const typeMatch = !state.activeType || shop.typeId === state.activeType;
			const keywordMatch = shop.name.includes(state.searchKeyword);
			return typeMatch && keywordMatch;
		});
	};

	// 获取轮播数据 
	const getBannerList = async () => {
		const {
			code,
			data
		} = await LifeCircleApi.getBannerList();
		if (code === 0) state.bannerList = data;
	};

	// 获取分类数据 
	const getGridList = async () => {
		const {
			code,
			data
		} = await LifeCircleApi.getStoreTypeList();
		if (code === 0) state.gridList.push(...data);
	};

	// 获取店铺数据 
	const getShopList = async () => {
		const {
			code,
			data
		} = await LifeCircleApi.getStoreList();
		if (code === 0) {
			state.originalShopList = data.map(shop => ({
				id: shop.id,
				typeId: shop.type,
				imageUrl: shop.logo,
				name: shop.name,
				address: shop.detailAddress,
				status: shop.status,
				discounts: shop.points,
				distance: `${Number(shop.distance).toFixed(1).replace(/\.?0+$/,  '')}km`,
			}));
			state.shopList = [...state.originalShopList];
		}
	};
	// 获取位置
	const getLocate = () => {
		uni.getLocation({
			type: 'wgs84',
			isHighAccuracy: true,
			success: function(res) {
				lngLat.value = [res.longitude, res.latitude]
				myAmapFun.value.getRegeo({
					location: res.longitude + ',' + res.latitude,
					success: res => {
						if (res?.[0]?.name) {
							locateContent.value = res?.[0]?.name
						}
					},
					fail: function(error) {
						console.log('高德地图受限')
						locateContent.value = ''
					}
				})

			}
		});
	}

	// 前往地图获取位置
	const getLocateMore = () => {
		sheep.$router.go('/pages/index/locate', {
			address: locateContent.value,
			longitude: lngLat.value[0],
			latitude: lngLat.value[1]
		});
	}

	onLoad(async (res) => {
		if (res.address) {
			locateContent.value = res.address
			lngLat.value = [res.longitude, res.latitude]
		} else {
			myAmapFun.value = new amap.AMapWX({
				key: '8c18837a8374f36e36d2d2884e9897b9'
			});
			getLocate()
		}

		await Promise.all([getBannerList(), getGridList(), getShopList()]);

	});
</script>

<style lang="scss" scoped>
	.s-category {
		:deep() {

			// 轮播图样式 
			.swiper-wrap {
				height: 300rpx;
				opacity: 0.7;

				.swiper-img {
					width: 100%;
					height: 100%;
					border-radius: 16rpx;
				}
			}

			// 定位的样式
			.locate {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				padding: 10rpx 20rpx;
				display: flex;
				align-items: center;
				background: rgba(255, 255, 255, 0.8);
				color: #000;

				.locate-content {
					width: 200rpx;
					overflow: hidden;
					white-space: nowrap;
					margin: 0 10rpx 4rpx;
				}

				.locate-icon {
					width: 32rpx;
					height: 32rpx;
				}
			}

			// 分类导航样式 
			.grid-wrap {
				display: grid;
				grid-template-columns: repeat(5, 1fr);
				gap: 20rpx;
				padding: 20rpx;

				.grid-item {
					display: flex;
					flex-direction: column;
					align-items: center;
					padding: 20rpx 10rpx !important; // 增加纵向间距 

					.icon-wrapper {
						margin-bottom: 16rpx; // 图标与文字间距 

						.grid-icon {
							width: 72rpx !important; // 放大图标尺寸 
							height: 72rpx !important;
						}
					}

					.text-wrapper {
						.grid-text {
							font-style: normal !important; // 强制取消斜体 
							font-size: 26rpx; // 放大字号 
							line-height: 1.4; // 增加行距 
							text-align: center;
							display: block;
							width: 100%;
							color: #333;
							font-weight: 400;
						}
					}

					// 激活状态优化 
					&.active-grid {
						.text-wrapper .grid-text {
							color: #1677ff !important;
							font-weight: 500 !important;
						}
					}
				}
			}

			// 店铺列表样式 
			.bottom-wrap {
				padding: 0 20rpx 20rpx;

				// 修改tab-bar区域样式 
				.tab-bar {
					display: flex;
					align-items: center; // 垂直居中 
					padding: 28rpx 20rpx;

					.tab-item {
						flex: none; // 禁止收缩 
						display: flex;
						align-items: center;

						// 标题图标样式 
						.title-icon {
							width: 48rpx; // 新增固定尺寸 
							height: 48rpx; // 保持图片比例 
							margin-right: 12rpx;
						}

						// 文字样式 
						.text-with-shadow {
							font-size: 36rpx;
							font-weight: bold;
							white-space: nowrap; // 禁止换行 
							color: #333;
						}
					}

					// 搜索框容器 
					.search-box {
						flex: 1; // 改为弹性填充 
						max-width: 450rpx; // 添加最大宽度限制 
						margin: 0 0 0 50rpx;
					}
				}

				.search-box {
					display: flex;
					align-items: center;
					padding: 20rpx 30rpx;
					margin: 20rpx;
					background: #f5f5f5;
					border-radius: 40rpx;

					.search-icon {
						width: 36rpx;
						height: 36rpx;
						margin-right: 16rpx;
					}

					.search-input {
						flex: 1;
						font-size: 28rpx;
						color: #333;
						height: 60rpx;
					}
				}

				.shop-list {
					padding: 24rpx;

					.shop-card {
						display: flex;
						padding: 24rpx;
						margin-bottom: 24rpx;
						background: #fff;
						border-radius: 16rpx;
						box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.03);

						&__thumb {
							width: 200rpx;
							height: 200rpx;
							border-radius: 12rpx;
							margin-right: 24rpx;
						}

						&__info {
							flex: 1;

							.name-status-wrapper {
								display: flex;
								justify-content: space-between;

								.shop-card__name {
									font-size: 32rpx;
									max-width: 75%;
								}

								.shop-card__status {
									font-style: normal;
									padding: 6rpx 20rpx;
									border-radius: 32rpx;
									font-size: 24rpx;

									&.active {
										background: #e8f6ef;
										color: #07c160;
									}

									&.inactive {
										background: #feeeed;
										color: #ff4141;
									}
								}
							}

							.star-rating {
								display: flex;
								margin: 12rpx 0;

								.star-icon {
									width: 28rpx;
									margin-right: 6rpx;
								}
							}

							.address-container {
								display: flex;
								justify-content: space-between;

								.shop-card__address {
									font-size: 26rpx;
									color: #444;
								}

								.distance-info {
									display: flex;
									align-items: center;

									.location-icon {
										width: 26rpx;
										height: 26rpx;
										margin-right: 6rpx;
									}

									.distance-text {
										font-size: 24rpx;
										color: #666;

										&::after {
											margin-left: 4rpx;
											color: #999;
										}
									}
								}
							}

							.discount-tags {
								display: flex;
								gap: 8rpx;
								margin-top: 12rpx;

								.discount-tag {
									border-radius: 4rpx;
									font-size: 22rpx;
									color: #2e7d32;

									.discount-tag-text {
										padding: 6rpx;
										font-weight: bold;
										background: #81c784;
										border: 1rpx solid #81c784;
									}

									.discount-tag-num {
										padding: 6rpx 14rpx;
										background-color: #e8f6ef;
										border: 1rpx solid #e8f6ef;
									}
								}


							}
						}
					}
				}
			}

			// 公共样式 
			.line-clamp-1 {
				display: -webkit-box;
				-webkit-line-clamp: 1;
				-webkit-box-orient: vertical;
				overflow: hidden;
			}
		}
	}
</style>